package com.singfan.common.util;

import com.singfan.common.SingFanException;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 随机工具类
 * Author: HanSongHe
 * Date: 2015-07-27 15:29
 * Desc:
 */
public class RandomUtil {
    /**
     * 根据权重做随机，然后返回列表索引
     * @param weights 权重列表
     * @return 列表索引
     */
    public static int selectByWeights(List<Integer> weights) {
        if (weights != null && weights.size() > 0){
            int result = 0;
            int total = 0;
            for (int weight : weights) {
                total += weight;
            }

            int r = new Random().nextInt(total)+1;
            int count = weights.size();
            for (int index = 0; index < count; index++) {
                r -= weights.get(index);
                if (r <= 0){
                    result = index;
                    break;
                }
            }
            return result;
        }
        else {
            throw new SingFanException("RandomUtil.selectByWeights() error: weights is null or empty !");
        }
    }

    /**
     * 根据权重做随机，然后返回随到的id
     * @param weights 权重map
     * @return 随到的id
     */
    public static Integer randomByWeights(Map<Integer, Integer> weights) {
        if (weights != null && weights.size() > 0) {
            Integer result = 0;
            int total = 0;
            for (Map.Entry<Integer, Integer> entry : weights.entrySet()) {
                total += entry.getValue();
            }

            int r = new Random().nextInt(total) + 1;
            for (Map.Entry<Integer, Integer> entry : weights.entrySet()) {
                r -= entry.getValue();
                if (r <= 0) {
                    result = entry.getKey();
                    break;
                }
            }
            return result;
        }
        else {
            throw new SingFanException("RandomUtil.randomByWeights() error: weights is null or empty !");
        }
    }

    /**
     * 命中百分比的结果
     * @param percent 百分比（1-100）
     * @return 命中结果
     */
    public static boolean hitPercent(int percent){
        if (percent >= 1 && percent <= 100){
            boolean result = false;
            if(new Random().nextInt(100) < percent){
                result = true;
            }
            return result;
        }
        else {
            throw new SingFanException(String.format("RandomUtil.randomByWeights() error: percent(%d) is not in [1,100] !", percent));
        }
    }

    /**
     * 随机生成一串数字
     * @param length 数字串的长度
     * @return 一串随机数字
     */
    public static String randomNumber(int length){
        String result = "";

        Random random = new Random();
        for (int i=0; i<length; i++){
            int num = random.nextInt(10);
            result += num;
        }

        return result;
    }
}
